﻿using System;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using BookSourceVerification.pool;
using Newtonsoft.Json.Linq;
using NLog;

namespace BookSourceVerification.handlers;

public class PingVerifyHandler : IHandler<JObject>
{
    private Logger _logger = LogManager.GetCurrentClassLogger();

    private PingPool _pingPool = new(110);

    public PingPool PingPool
    {
        get => _pingPool;
        set { _pingPool = value; }
    }

    public bool IsChecked(JObject node, HandlerResult result)
    {
        if (result.Data is string) return true;
        _logger.Error("url为空");
        return false;

    }

    public async Task DoHandler(JObject node, HandlerResult result)
    {
        string url = (result.Data as string)!;
        Ping? ping = null;
        PingReply reply;
        try
        {
            var host = GetHost(url);
            ping = _pingPool.Acquire();
            reply = await ping.SendPingAsync(host);
            if (reply.Status == IPStatus.Success)
            {
                result.Success();
            }
            else
            {
                result.Fail();
            }
        }
        catch (Exception e)
        {
            _logger.Error(e);
            result.Fail();
        }
        finally
        {
            if (ping is not null)
            {
                _pingPool.Release(ping);
            }
        }
    }

    public void AfterHandler()
    {
    }

    private static string GetHost(string url)
    {
        var uri = new Uri(url);
        var host = uri.Host;
        return host;
    }
}